"""
Basic usage example for the Wan 2.2 API client.

This script demonstrates how to use the WanClient to submit video generation tasks
and monitor their progress.
"""
import asyncio
import os
from pathlib import Path
from datetime import datetime

# Add the parent directory to the path so we can import the client
import sys
sys.path.insert(0, str(Path(__file__).parent.parent))

from client import WanClient, TaskStatus

# Configuration
API_BASE_URL = "http://localhost:8000"  # Update with your API URL
API_KEY = os.getenv("WAN_API_KEY")      # Optional, if authentication is enabled

async def main():
    # Initialize the client
    print("Initializing Wan 2.2 API client...")
    client = WanClient(base_url=API_BASE_URL, api_key=API_KEY)
    
    try:
        # Example 1: Text to Video
        print("\n=== Example 1: Text to Video ===")
        print("Submitting text-to-video task...")
        t2v_task = await client.text_to_video(
            prompt="A beautiful sunset over mountains, cinematic, 8K",
            duration_seconds=5,
            resolution="720p"
        )
        print(f"Task submitted! Task ID: {t2v_task.task_id}")
        
        # Wait for the task to complete
        print("\nWaiting for task to complete...")
        try:
            result = await client.wait_for_task_completion(t2v_task.task_id, poll_interval=2.0)
            print(f"\nTask completed! Status: {result.status}")
            if result.status == TaskStatus.COMPLETED:
                print(f"Video URL: {result.result.get('video_url')}")
            else:
                print(f"Error: {result.error}")
        except asyncio.TimeoutError:
            print("Timed out waiting for task to complete")
        
        # Example 2: Image to Video (without waiting)
        print("\n=== Example 2: Image to Video ===")
        print("Submitting image-to-video task...")
        i2v_task = await client.image_to_video(
            image_url="https://example.com/input.jpg",  # Replace with a real image URL
            prompt="Make the image come to life with gentle movement",
            duration_seconds=4,
            resolution="720p",
            motion_strength=0.4
        )
        print(f"Task submitted! Task ID: {i2v_task.task_id}")
        print("This task is running in the background. You can check its status later.")
        
        # Example 3: Check task status
        print("\n=== Example 3: Check Task Status ===")
        task_id = input("Enter a task ID to check status (or press Enter to skip): ")
        if task_id.strip():
            try:
                status = await client.get_task_status(task_id)
                print(f"\nTask Status:")
                print(f"- ID: {status.task_id}")
                print(f"- Status: {status.status}")
                print(f"- Created at: {datetime.fromtimestamp(status.created_at).isoformat()}")
                print(f"- Updated at: {datetime.fromtimestamp(status.updated_at).isoformat()}")
                
                if status.status == TaskStatus.COMPLETED and status.result:
                    print("\nResult:")
                    for key, value in status.result.items():
                        print(f"- {key}: {value}")
                elif status.status == TaskStatus.FAILED and status.error:
                    print(f"\nError: {status.error}")
            except Exception as e:
                print(f"Error: {str(e)}")
        
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        import traceback
        traceback.print_exc()
    
    print("\nDone!")

if __name__ == "__main__":
    asyncio.run(main())
